<?php

namespace Modules\H5\Http\Controllers\Activation;

use Illuminate\Support\Facades\DB;
use Modules\Common\Models\ActivationCodeUsage;
use Modules\Common\Models\ActivationCodeLogs;
use Modules\Common\Models\ActivationCodes;
use Modules\Common\Models\SubscriptionRecords;
use Modules\Common\Models\Members;
use Modules\Common\Models\SubscriptionTypes;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use Carbon\Carbon;

class Activation
{
    /**
     * 获取激活卡兑换记录
     * @Route(path=/api/h5/activation-records)
     */
    public function activationRecords()
    {

        $userId = auth('web')->user()->id; //获取当前认证的用户ID

        $query = ActivationCodeUsage::with(['subscriptionTypes'])->where('user_id', $userId);
        // 获取分页数据
        $data  = $query->orderByRaw('id desc , created_at desc')->paginate(request('per_page', 15));

        return Api::success($data);
    }
    
    
    /**
     * 激活码兑换
     * @Route(path=/api/h5/activation-code-exchange method=post)
     */
    public function exchange()
    {
        $code = request('code');
        $autoRenew = request('auto_renew', '2');
        $userId = auth('web')->user()->id;
        $eid = auth('web')->user()->eid;
    
        // 查找激活码
        $activationCode = ActivationCodes::where('code', $code)
            ->where('eid', $eid)
            ->where('status', '<>', 2) // 不等于已使用状态
            ->where('status', '<>', 3) // 不等于已过期状态
            ->first();
    
        // 验证激活码是否存在以及是否有效
        if (!$activationCode) {
            return Api::fail('激活码不存在或已使用/过期', 404);
        }
    
        // 兑换会员处理
        $subscriptionType = SubscriptionTypes::find($activationCode->subscription_type_id);
        if (!$subscriptionType) {
            return Api::fail('订阅类型不存在', 404);
        }
    
        DB::beginTransaction();
        try {
            $member = Members::where('user_id', $userId)->first();
    
            if ($member) {
                // 确保 end_date 是 Carbon 实例
                $currentEndDate = Carbon::parse($member->end_date);
            
                // 如果会员记录存在且还未到期，更新到期日期
                if ($currentEndDate->gt(Carbon::now())) {
                    if ($subscriptionType->duration == -1) {
                        // 如果新订阅是永久的，设置为特定远期日期
                        $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                    } else {
                        // 否则在现有基础上增加时长
                        if($currentEndDate = "9999-12-31 00:00:00"){
                            $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                        }else{
                            $newEndDate = $newEndDate->addDays($subscriptionType->duration);
                        }
                    }
                } else {
                    // 如果会员已经到期，设置新的开始和结束日期
                    $newEndDate = now();
                    if ($subscriptionType->duration == -1) {
                        $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                    } else {
                        if($currentEndDate = "9999-12-31 00:00:00"){
                            $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                        }else{
                            $newEndDate = $newEndDate->addDays($subscriptionType->duration);
                        }
                    }
                }
            
                // 更新会员记录
                $member->update([
                    'level_id' => $subscriptionType->id,
                    'status' => 1,
                    'payment_method' => 3,
                    'subscription_type_id' => $subscriptionType->id,
                    'membership_fee' => $subscriptionType->price,
                    'auto_renew' => $autoRenew,
                    'start_date' => now(),
                    'end_date' => $newEndDate,
                ]);
            } else {
                // 如果不存在，创建新的会员记录
                $member = Members::create([
                    'user_id' => $userId,
                    'level_id' => $subscriptionType->id,
                    'status' => 1,
                    'payment_method' => 3,
                    'subscription_type_id' => $subscriptionType->id,
                    'membership_fee' => $subscriptionType->price,
                    'auto_renew' => $autoRenew,
                    'start_date' => now(),
                    'end_date' => $subscriptionType->duration == -1 ? Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay() : now()->addDays($subscriptionType->duration),
                ]);
            }
    
            // 标记激活码为已使用
            $activationCode->update(['status' => 2]);
    
            // 创建激活码使用记录
            ActivationCodeUsage::create([
                'user_id' => $userId,
                'subscription_type_id' => $subscriptionType->id,
                'used_time' => now(),
                'code' => $activationCode->code,
                'eid' => $eid
            ]);
    
            DB::commit();
            return Api::success($member);
        } catch (\Exception $e) {
            DB::rollBack();
            return Api::fail($e->getMessage(), 500);
        }
    }
    
}